﻿using Estsh.Core.Controllers;
using Estsh.Core.Model.ExcelModel;
using Estsh.Core.Model.Result;
using Estsh.Core.Models;
using Estsh.Core.Wms.IServices;
using Estsh.Core.Util;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using Estsh.Core.Model.Extend.Models;
using Estsh.Core.Model.EnumUtil;




/***************************************************************************************************
 *
 * 更新人：sitong.dong
 * 描述：采购单管理
 * 修改时间：2022.06.22
 * 修改日志：系统迭代升级
 *
 **************************************************************************************************/
namespace Estsh.Core.Web.Plugin.Wms
{
    [Area("wms")]
    public class PurchaseManageController : BaseController
    {
        private IPurchaseManageService service;
        public PurchaseManageController(IPurchaseManageService _service)
        {
            service = _service;
        }
        //
        // GET: /Menu/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取采购单管理列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getPurchaseListByPage(string orderNo,string orderType,string orderStatus, string startTime, string endTime, Pager pager, String direction, String sort, string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            result.Add("pager.pageNo", pager.pageNo);
            Hashtable dataHt = this.service.getPurchaseListByPage(orderNo, orderType, orderStatus, startTime, endTime, enabled, factoryId, pager, direction, sort);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            result.Add("sort", sort);
            result.Add("direction", direction);
            return Json(result);
        }

        /// <summary>
        /// 获取采购单管理明细列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getPurchaseDetailListByPage(string orderNo, string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            Hashtable dataHt = this.service.getPurchaseDetailListByPage(orderNo, enabled, factoryId);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            return Json(result);
        }

        /// <summary>
        /// 获取库存明细列表数据
        /// </summary>
        /// <param name="menuName"></param>
        /// <param name="pager"></param>
        /// <param name="direction"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ActionResult getStockListByPage(string orderNo, string partNo, string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            Hashtable result = new Hashtable();
            Hashtable dataHt = this.service.getStockListByPage(orderNo, partNo, enabled, factoryId);
            result.Add("rows", dataHt["dataList"]);
            result.Add("pager.totalRows", dataHt["totalCount"]);
            return Json(result);
        }

        //打印查询
        public ActionResult getStockListByPrint(string orderNo, string enabled = "Y")
        {
            int factoryId = CurrentEmp.FactoryId;
            List<SysStock> listData = this.service.getStockListByPrint(orderNo, enabled, factoryId);
            return Json(listData);
        }

        /// <summary>
        /// 获取父节点菜单下拉列表数据
        /// </summary>
        /// <rehuoturns></returns>
        public ActionResult getSelectFactory()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectFactory();
            result.Add("list", menuList);
            return Json(result);
        }

        public ActionResult getSelectWarehouse()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectWarehouse();
            result.Add("list", menuList);
            return Json(result);
        }

        public ActionResult getSelectZone()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectZone();
            result.Add("list", menuList);
            return Json(result);
        }
        public ActionResult getSelectVendor()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.getSelectVendor();
            result.Add("list", menuList);
            return Json(result);
        }
        public ActionResult GetPart()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetPart();
            result.Add("list", menuList);
            return Json(result);
        }
        public ActionResult GetOrderType()
        {
            Hashtable result = new Hashtable();
            List<KeyValueResult> menuList = this.service.GetOrderType();
            result.Add("list", menuList);
            return Json(result);
        }
        /// <summary>
        /// 保存菜单数据
        /// </summary>
        /// <returns></returns>
        public ActionResult savePurchaseManage()
        {
            int orderType = int.Parse(Request.Form["orderType"]);
            String vendorName = Request.Form["vendorName"].ToString();
            String seDate = string.IsNullOrEmpty(Request.Form["seDate"]) ? "" : Convert.ToDateTime(Request.Form["seDate"].ToString()).ToString("yyyymmdd");
            String seTime = string.IsNullOrEmpty(Request.Form["seTime"]) ? "" : Convert.ToDateTime(Request.Form["seTime"].ToString()).ToString("HHmmss");
            String dock = Request.Form["dock"].ToString();
            String enabled = Request.Form["enabled"].ToString();

            String item_no = Request.Form["item_no"].ToString();
            String PartNo = string.IsNullOrEmpty(Request.Form["PartNo"]) ? "0" : Request.Form["PartNo"];
            String qty = Request.Form["qty"].ToString();
            String recQty = "0";//已收数量
            String boxQty = Request.Form["boxQty"].ToString();
            String recBoxQty = "0";//已收包装数量
            String snpQty = Request.Form["snpQty"].ToString();
            String unit = "";
            String erpWarehouse = Request.Form["erpWarehouse"].ToString();
            String itemStatus = Request.Form["itemStatus"].ToString();

            string detailRow = Request.Form["detailRow"].ToString();

            int vendorId = 0;
            string vendorCode = "";
            List<SysVendor> sysVendors = service.getSelectVendor(vendorName);
            if (sysVendors.Count > 0)
            {
                vendorId = sysVendors[0].VendorId;
                vendorCode = sysVendors[0].VendorCode;
            }
           

            WmsPurchase purchase = new WmsPurchase();
            purchase.OrderType = orderType;
            purchase.VendorId = vendorId;
            purchase.VendorCode = vendorCode;

            purchase.SeDate = seDate;
            purchase.SeTime = seTime;
            purchase.Dock = dock;
            purchase.Enabled = enabled;
            purchase.FactoryId = CurrentEmp.FactoryId;
            purchase.FactoryCode = CurrentEmp.FactoryCode;

            IList<WmsPurchaseDetail> purchaseDetailList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WmsPurchaseDetail>>(detailRow);
            for (int i = 0; i < purchaseDetailList.Count; i++)
            {
                purchaseDetailList[i].ItemNo = (i + 1).ToString();
                //purchaseDetailList[i].PartId = Convert.ToInt32(PartId);
                PartNo = string.IsNullOrEmpty(purchaseDetailList[i].PartNo.ToString())?"0": purchaseDetailList[i].PartNo.ToString();
                List<SysPart> parts = service.GetPart(PartNo);
                if (parts.Count > 0)
                {
                    purchaseDetailList[i].PartId = parts[0].PartId;
                    purchaseDetailList[i].PartSpec = parts[0].PartSpec;
                    purchaseDetailList[i].Unit = parts[0].Unit;
                }
                else
                {
                    purchaseDetailList[i].PartId = 0;
                    purchaseDetailList[i].PartSpec = "";
                    purchaseDetailList[i].Unit = "";
                }
                purchaseDetailList[i].RecQty = string.IsNullOrEmpty(recQty) ? 0 : Convert.ToDecimal(recQty);
                purchaseDetailList[i].BoxQty = string.IsNullOrEmpty(boxQty) ? 0 : Convert.ToDecimal(boxQty);
                purchaseDetailList[i].RecBoxQty = string.IsNullOrEmpty(recBoxQty) ? 0 : Convert.ToDecimal(recBoxQty);
                purchaseDetailList[i].SnpQty = string.IsNullOrEmpty(snpQty) ? 0 : Convert.ToDecimal(snpQty);
                //purchaseDetailList[i].ErpWarehouse = erpWarehouse;
                purchaseDetailList[i].ItemStatus = (int)WmsEnumUtil.PurchaseOrderDetailStatus.CREATE;
                purchaseDetailList[i].Enabled = enabled;
                purchaseDetailList[i].FactoryId = CurrentEmp.FactoryId;
                purchaseDetailList[i].FactoryCode = CurrentEmp.FactoryCode;
                purchaseDetailList[i].CreateUserId = CurrentEmp.EmpId;
            }
            String message = "";
            String status = "0";

            try
            {
                purchase.CreateUserId = CurrentEmp.EmpId;
         
                int ret = this.service.savePurchaseManage(purchase, purchaseDetailList);
                if (ret > 0)
                {
                    status = "1";
                    message = "添加成功";
                }
                else
                {
                    status = "0";
                    message = "添加失败！";
                }
            }
            catch (Exception e)
            {
                status = "0";
                message = "添加失败！";
            }

            Hashtable result = new Hashtable();
            result.Add("status", status);
            result.Add("message", message);
            return Json(result);
        }
        public ActionResult GetErpwarehouse()
        {
            Hashtable resault = new Hashtable();
            List<KeyValueResult> pdlineList = service.GetErpwarehouse();
            resault.Add("list", pdlineList);
            return Json(resault);
        }

        public ActionResult GetOrderStatus()
        {
            Hashtable resault = new Hashtable();
            List<KeyValueResult> pdlineList = service.GetOrderStatus();
            resault.Add("list", pdlineList);
            return Json(resault);
        }

        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult EditPurchaseManage(String warehouseId)
        {
            //if (!string.IsNullOrEmpty(warehouseId))
            //{
            //    Hashtable ht = this.service.getWarehouseDetail(warehouseId);
            //    ViewData.Add("editType", "edit");
            //    ViewData.Add("warehouseId", ht["warehouseId"]);
            //    ViewData.Add("factoryId", ht["factoryId"]);
            //    ViewData.Add("factoryName", ht["factoryName"]);
            //    ViewData.Add("warehouseName", ht["warehouseName"]);
            //    ViewData.Add("warehouseDesc", ht["warehouseDesc"]);

            //    ViewData.Add("enabled", ht["enabled"]);
            //}
            //else
            //{
            ViewData.Add("editType", "new");
            //}
            return View("EditPurchaseManage");
        }

        /// <summary>
        /// 生成条码
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult onBarcodeGenerator(String orderNos)
        {
            Hashtable result = new Hashtable();
            try
            {
                string userId = CurrentEmp.EmpId.ToString();
                string factoryId = CurrentEmp.FactoryId.ToString();
                string factoryCode = CurrentEmp.FactoryCode;
                result = this.service.onBarcodeGenerator(orderNos, userId,factoryId,factoryCode);
            }
            catch (Exception e)
            {
                result.Add("message", "生成条码失败，请重查看！");
                result.Add("flag", "error");
            }
            return Json(result);
        }


        #region 过滤零件号
        public ActionResult GetPart_No(string q)
        {
            List<string> list = filePart(q);
            return writeResult(list);
        }

        /// <summary>
        /// 过滤零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<string> filePart(string key)
        {
            Hashtable autoComplateList = GetItemPart(key);
            List<String> result = new List<string>();
            foreach (System.Collections.DictionaryEntry item in autoComplateList)
            {
                if (item.Value.ToString().ToUpper().StartsWith(key.ToUpper()))
                {
                    result.Add(item.Value.ToString());
                }
            }
            return result;
        }
        /// <summary>
        /// 查询零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Hashtable GetItemPart(string key)
        {
            List<String> autoComplateList = new List<string>();
            Hashtable result = new Hashtable();

            try
            {
                List<SysPart> dt = service.GetPartNoInfo(key);
                for (int i = 0; i < dt.Count; i++)
                {
                    result.Add(dt[i].PartId.ToString(), dt[i].PartNo.ToString());

                }
            }
            catch (Exception e)
            {
                result = new Hashtable();
            }
            return result;
        }
        #endregion

        #region 过滤零件号简码
        public ActionResult GetPart_Spec(string q)
        {
            List<string> list = filePartSpec(q);
            return writeResult(list);
        }

        /// <summary>
        /// 过滤零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<string> filePartSpec(string key)
        {
            Hashtable autoComplateList = GetItemPartSpec(key);
            List<String> result = new List<string>();
            foreach (System.Collections.DictionaryEntry item in autoComplateList)
            {
                if (item.Value.ToString().ToUpper().StartsWith(key.ToUpper()))
                {
                    result.Add(item.Value.ToString());
                }
            }
            return result;
        }
        /// <summary>
        /// 查询零件号
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Hashtable GetItemPartSpec(string key)
        {
            List<String> autoComplateList = new List<string>();
            Hashtable result = new Hashtable();

            try
            {
                List<SysPart> dt = service.GetPartSpecInfo(key);
                for (int i = 0; i < dt.Count; i++)
                {
                    result.Add(dt[i].PartId.ToString(), dt[i].PartSpec.ToString());
                }
            }
            catch (Exception e)
            {
                result = new Hashtable();
            }
            return result;
        }
        #endregion
        private ActionResult writeResult(List<string> list)
        {
            Hashtable result = new Hashtable();
            result.Add("list", list);
            return Json(result);
        }

        public ActionResult getPartNoInfo(string partNo)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartNoInfo(partNo);
            return Json(list);
        }
        public ActionResult getPartNoInfoByPartNo(string partNo)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartNoInfoByPartNo(partNo);
            return Json(list);
        }

        public ActionResult getPartSpecInfo(string partSpec)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartSpecInfo(partSpec);
            return Json(list);
        }
        public ActionResult getPartSpecInfoByPartSpec(string partSpec)
        {
            Hashtable resault = new Hashtable();
            List<SysPart> list = service.GetPartSpecInfoByPartSpec(partSpec);
            return Json(list);
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="ruid"></param>
        /// <returns></returns>
        public ActionResult onClose(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.onClose(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 启用
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult onEnable(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.EnableData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult onDisable(String orderNos)
        {
            int delCount = 0;
            try
            {
                delCount = this.service.DisableData(orderNos);
            }
            catch (Exception e)
            {
                delCount = -1;
            }
            Hashtable result = new Hashtable();
            result.Add("status", delCount);
            return Json(result);
        }

    }
}
